<template>
  <span class="count-down">
    {{leaveTime | toLeaveTime}}
  </span>
</template>

<script>
  export default {
    name: 'count-down',
    props: {
      time: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        timer: null,
        leaveTime: this.time ? parseInt((new Date(this.time).getTime() - new Date().getTime()) / 1000) : ''
      }
    },
    created () {
      clearInterval(this.timer)
      this.startCount()
    },
    methods: {
      startCount () {
        this.timer = setInterval(() => {
          if (this.leaveTime <= 0) {
            clearInterval(this.timer)
            // TODO 倒计时结束 处理某些事件
          } else {
            this.leaveTime -= 1
          }
        }, 1000)
      }
    },
    filters: {
      /**
       * 格式化剩余时间
       * @param leaveSeconds {number} 传入剩余秒数
       */
      toLeaveTime (leaveSeconds) {
        function checkTime (i) { // 将0-9的数字前面加上0，例1变为01
          if (i < 10) {
            i = '0' + i
          }
          return i
        }
        let time = ''
        let days = Math.floor(leaveSeconds / (60 * 60 * 24))// 天数
        let modulo = leaveSeconds % (60 * 60 * 24)// 取模（余数）
        let hours = checkTime(Math.floor(modulo / (60 * 60)))// 小时数
        modulo = modulo % (60 * 60)
        let minutes = checkTime(Math.floor(modulo / 60)) // 分钟
        let seconds = checkTime(modulo % 60) // 秒

        if (leaveSeconds <= 0) {
          time = '00:00:00'
        } else {
          if (days) {
            hours = days * 24 + hours / 1
            time = hours + ':' + minutes + ':' + seconds
          } else {
            time = hours + ':' + minutes + ':' + seconds
          }
        }
        return time
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
